// utils.js - 提供工具函数

// 表单验证
const Validator = {
    // 验证是否为有效的手机号码
    isPhoneNumber: function(phone) {
        const reg = /^1[3-9]\d{9}$/;
        return reg.test(phone);
    },

    // 验证是否为有效的邮箱
    isEmail: function(email) {
        const reg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
        return reg.test(email);
    },

    // 验证是否为有效的身份证号
    isIdCard: function(idCard) {
        // 简化版验证，实际应用中可能需要更复杂的验证
        const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
        return reg.test(idCard);
    },

    // 验证是否为有效的日期格式 (YYYY-MM-DD)
    isDate: function(date) {
        const reg = /^(\d{4})-(\d{2})-(\d{2})$/;
        if (!reg.test(date)) return false;

        const [, year, month, day] = date.match(reg);
        const d = new Date(year, month - 1, day);
        return d.getFullYear() == year && d.getMonth() + 1 == month && d.getDate() == day;
    },

    // 验证是否为有效的金额
    isMoney: function(money) {
        const reg = /^\d+(\.\d{1,2})?$/;
        return reg.test(money);
    },

    // 验证是否为纯数字
    isNumber: function(num) {
        const reg = /^\d+$/;
        return reg.test(num);
    },

    // 验证是否为中文
    isChinese: function(chinese) {
        const reg = /^[\u4e00-\u9fa5]+$/;
        return reg.test(chinese);
    },

    // 验证字符串长度范围
    isLengthBetween: function(str, min, max) {
        return str.length >= min && str.length <= max;
    }
};

// 数据格式化
const Formatter = {
    // 格式化日期 (YYYY-MM-DD)
    formatDate: function(date) {
        if (!date) return '';

        if (typeof date === 'string') {
            date = new Date(date);
        }

        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');

        return `${year}-${month}-${day}`;
    },

    // 格式化日期时间 (YYYY-MM-DD HH:mm:ss)
    formatDateTime: function(date) {
        if (!date) return '';

        if (typeof date === 'string') {
            date = new Date(date);
        }

        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');

        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    // 格式化金额 (保留两位小数)
    formatMoney: function(money) {
        return parseFloat(money).toFixed(2);
    },

    // 格式化手机号码 (138****8888)
    formatPhone: function(phone) {
        if (!phone || phone.length !== 11) return phone;
        return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
    },

    // 首字母大写
    firstLetterUpper: function(str) {
        if (!str) return '';
        return str.charAt(0).toUpperCase() + str.slice(1);
    },

    // 千位分隔符
    formatThousands: function(num) {
        return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    }
};

// DOM操作工具
const DOMUtils = {
    // 获取URL参数
    getUrlParam: function(name) {
        const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`);
        const r = window.location.search.substr(1).match(reg);
        if (r != null) return decodeURIComponent(r[2]);
        return null;
    },

    // 设置URL参数
    setUrlParam: function(name, value) {
        const url = window.location.href;
        const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`);
        if (url.match(reg)) {
            return url.replace(reg, `$1${name}=${encodeURIComponent(value)}$3`);
        } else {
            return url.indexOf('?') > -1 ?
                `${url}&${name}=${encodeURIComponent(value)}` :
                `${url}?${name}=${encodeURIComponent(value)}`;
        }
    },

    // 防抖函数
    debounce: function(func, wait) {
        let timeout;
        return function() {
            const context = this;
            const args = arguments;
            clearTimeout(timeout);
            timeout = setTimeout(() => func.apply(context, args), wait);
        };
    },

    // 节流函数
    throttle: function(func, wait) {
        let previous = 0;
        return function() {
            const now = Date.now();
            const context = this;
            const args = arguments;
            if (now - previous > wait) {
                func.apply(context, args);
                previous = now;
            }
        };
    },

    // 平滑滚动到顶部
    scrollToTop: function() {
        const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
        if (scrollTop > 0) {
            window.requestAnimationFrame(this.scrollToTop);
            window.scrollTo(0, scrollTop - scrollTop / 8);
        }
    },

    // 显示加载提示
    showLoading: function() {
        let loading = document.getElementById('loading');
        if (!loading) {
            loading = document.createElement('div');
            loading.id = 'loading';
            loading.style.cssText = 'position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); display: flex; justify-content: center; align-items: center; z-index: 9999';
            loading.innerHTML = '<div style="text-align: center; background-color: #fff; padding: 20px; border-radius: 5px;"><div style="width: 50px; height: 50px; border: 5px solid #f3f3f3; border-top: 5px solid #3498db; border-radius: 50%; margin: 0 auto; animation: spin 1s linear infinite;"></div><p style="margin-top: 15px;">加载中...</p></div>';
            document.body.appendChild(loading);
        }
    },

    // 隐藏加载提示
    hideLoading: function() {
        const loading = document.getElementById('loading');
        if (loading) {
            document.body.removeChild(loading);
        }
    },

    // 显示提示框
    showToast: function(message, duration = 2000) {
        let toast = document.getElementById('toast');
        if (!toast) {
            toast = document.createElement('div');
            toast.id = 'toast';
            toast.style.cssText = 'position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background-color: rgba(0, 0, 0, 0.7); color: #fff; padding: 10px 20px; border-radius: 5px; z-index: 9999;';
            document.body.appendChild(toast);
        }
        toast.textContent = message;
        toast.style.display = 'block';
        setTimeout(() => {
            toast.style.display = 'none';
        }, duration);
    },

    // 绑定事件
    on: function(element, event, handler) {
        if (element.addEventListener) {
            element.addEventListener(event, handler, false);
        } else if (element.attachEvent) {
            element.attachEvent('on' + event, handler);
        } else {
            element['on' + event] = handler;
        }
    },

    // 解绑事件
    off: function(element, event, handler) {
        if (element.removeEventListener) {
            element.removeEventListener(event, handler, false);
        } else if (element.detachEvent) {
            element.detachEvent('on' + event, handler);
        } else {
            element['on' + event] = null;
        }
    },

    // 淡入效果
    fadeIn: function(element, duration = 500) {
        element.style.opacity = '0';
        element.style.display = 'block';
        let start = null;
        function step(timestamp) {
            if (!start) start = timestamp;
            const progress = Math.min((timestamp - start) / duration, 1);
            element.style.opacity = progress;
            if (progress < 1) {
                window.requestAnimationFrame(step);
            }
        }
        window.requestAnimationFrame(step);
    },

    // 淡出效果
    fadeOut: function(element, duration = 500) {
        element.style.opacity = '1';
        let start = null;
        function step(timestamp) {
            if (!start) start = timestamp;
            const progress = Math.min((timestamp - start) / duration, 1);
            element.style.opacity = 1 - progress;
            if (progress < 1) {
                window.requestAnimationFrame(step);
            } else {
                element.style.display = 'none';
            }
        }
        window.requestAnimationFrame(step);
    }
};

// 添加旋转动画样式
const spinAnimationStyle = document.createElement('style');
spinAnimationStyle.textContent = '@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }';
document.head.appendChild(spinAnimationStyle);

// 为了兼容模块化和非模块化环境
// ES6模块导出
 // 暴露到全局对象
window.Validator = Validator;
window.Formatter = Formatter;
// export { Validator, Formatter };

// 兼容旧版非模块环境
if (typeof window !== 'undefined') {
    window.Validator = Validator;
    window.Formatter = Formatter;
}